<template>
	<view>
		<u-upload :fileList="fileList" 
              @customPreview="customPreview" 
              :name="name" 
              :previewFullImage="true"
              @afterRead="afterRead" 
              @delete="deletePic" 
              multiple 
              :maxCount="isEdit?limit:fileList.length"
              :deletable="deletable" 
              style="width: 100rpx;height: 100rpx;">
		</u-upload>
	</view>
</template>

<script>
import configService from '@/common/service/config.service.js'
import UUpload from '@/uni_modules/uview-ui/components/u-upload/u-upload.vue';
	import {
		httpResources
	} from "@/tool/index.js"
	
export default {
  name: "uploadMedia",
  components: { UUpload },
  props: {
    name: {
      type: String,
      default: '1'
    },
    limit: {
      type: Number,
      default: 1
    },
    value: [String, Number],
    deletable: {
      type: Boolean,
      default: true
    },
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fileList: [],
      previewShow: false,
      previewImg: ''
    };
  },
  watch: {
    value: {
      handler(newVal) {
        this.fileList = [];
        if (newVal) {
          const paths = newVal.toString().split(',').filter(Boolean);
          paths.forEach(path => {
            this.fileList.push({
              type: 'image',
              url:httpResources(path),
              id: path,
              path: path
            });
          });
        }
      },
      immediate: true
    }
  },
  methods: {
    async afterRead(event) {
      const lists = [].concat(event.file);
      const fileListLen = this.fileList.length;
      
      // 添加上传状态
      lists.forEach(item => {
        this.fileList.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        });
      });

      try {
        for (let i = 0; i < lists.length; i++) {
          uni.showLoading({ title: '上传中...', mask: true });
          
          const result = await this.uploadFilePromise(lists[i].thumb);
          if (!result.success) throw new Error(result.message);

          const index = fileListLen + i;
          const { path } = result.data;

          this.$set(this.fileList, index, {
            ...lists[i],
            status: 'success',
            message: '',
            url: httpResources(path),
            id: path,
            path: path
          });
        }

        this.emitUpdate();
      } catch (error) {
        console.error('上传失败:', error);
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        });
        // 标记失败状态
        const failIndex = fileListLen + lists.length - 1;
        this.$set(this.fileList, failIndex, {
          ...this.fileList[failIndex],
          status: 'failed',
          message: error.message || '上传失败'
        });
      } finally {
        uni.hideLoading();
      }
    },

    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: "http://localhost:3001/api/upload",
          filePath: url,
          name: 'file',
          header: {
            'token': uni.getStorageSync('token') || '',
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data);
              if (data.code === 0 && data.success) {
                resolve(data);
              } else {
                reject(new Error(data.message || '上传失败'));
              }
            } catch (e) {
              reject(new Error('响应解析失败'));
            }
          },
          fail: (err) => {
            reject(new Error('网络连接失败'));
          }
        });
      });
    },

    deletePic(event) {
      const delPath = this.fileList[event.index]?.path;
      if (!delPath) return;

      this.fileList = this.fileList.filter(item => item.path !== delPath);
      this.emitUpdate();
    },

    customPreview(event) {
      const fullUrls = this.fileList
        .filter(item => item.status === 'success')
        .map(item => item.url);

      if (fullUrls.length > 0) {
        uni.previewImage({
          current: fullUrls.indexOf(event.url),
          urls: fullUrls
        });
      }
    },

    emitUpdate() {
      const validPaths = this.fileList
        .filter(item => item.status === 'success')
        .map(item => item.path);

      this.$emit("input", validPaths.join(','));
      this.$emit("change", validPaths);
    }
  }
}
</script>

<style>
.images {
  width: 100px;
  height: 100px;
}
</style>